const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const Body = require('koa-body')
const fs = require('fs')

const apiRouter = new Router()
app.use(Body({
  multipart: true
}))

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')
  await next()
})

apiRouter.post('/',async ctx => {
  console.log(ctx.request.body)
  const data = ctx.request.body
  // console.log(data.url);

  fs.readdir(data.url, function(err, files){
    if (err){
      // console.log(err)
      return
    }
    files.forEach(fileName => {
      const url = data.url + fileName
      fs.stat(url, function(err, file){
        if (err) {
          // console.log(err)
        }
        // console.log(file);
      })
    });
  })

  ctx.body = { 
    token:'abc', 
    msg:'ok'
  };
})

function sayHello(name){
  const messages = require('./helloworld_pb')
  const services = require('./helloworld_grpc_pb')
  const grpc = require('grpc')
  const client = new services.GreeterClient(
    'localhost:50051',
    grpc.credentials.createInsecure()
  )
  const request = new messages.HelloRequest()
  const user = name
  request.setName(user)
  return new Promise(function (resolve, reject) {
    client.sayHello(request, function (err, response) {
      if (err)reject(err)
      resolve(response.getMessage())
    })
  });
}

apiRouter.post('/hello', async ctx =>{
  console.log(ctx.request.body);
  const data = ctx.request.body
  await sayHello(data.name).then(res=>{
    ctx.body = { 
      data: res,
      msg:'ok'
    };
  })
  // const messages = require('./helloworld_pb')
  // const services = require('./helloworld_grpc_pb')
  // const grpc = require('@grpc/grpc-js')
  // const client = new services.GreeterClient(
  //   'localhost:50051',
  //   grpc.credentials.createInsecure()
  // )
  // const request = new messages.HelloRequest()
  // const user = data.name
  // request.setName(user)
  // return client.sayHello(request, function (err, response) {
  //   console.log(err);
  //   console.log(response.getMessage())
  //   const res = response.getMessage()
  //   ctx.body = { 
  //     data: res,
  //     msg:'ok'
  //   };
  // })
  // ctx.body = { 
  //   data: res,
  //   msg:'ok'
  // };
})

app.use(apiRouter.routes(), apiRouter.allowedMethods());

app.use(function* (next){
  const start = new Date;
  yield next;
  const ms = new Date - start; 
  console.log('%s %s - %s', this.method, this.url, ms); // 显示执行的时间
});

app.listen(4000, ()=>{
  console.log('start successfully!');
})

module.exports = app;